import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.DataEvent;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.MediaEvent;
import flash.events.MouseEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.media.CameraRoll;
import flash.media.CameraUI;
import flash.media.MediaPromise;
import flash.media.MediaType;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
import flash.utils.IDataInput;

import mx.graphics.codec.JPEGEncoder;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;

//private var urlRequest:URLRequest = new URLRequest("http://twitaddons.com/photo/upload_mobile.php");
//private var urlRequest:URLRequest = new URLRequest("http://twitaddons.com/msg/msg_upload_pic_mobile.php");
private var urlRequest:URLRequest = new URLRequest();
private var uploadTargetUrl:String = "http://twitaddons.com/photo/upload_mobile.php";

private var file:File;


/*
//take a new picture with the camera
protected function uploadCamera_clickHandler(event:MouseEvent):void
{
if (CameraUI.isSupported)
{
trace("camera is supported");
var myCam:CameraUI = new CameraUI();
myCam.launch(MediaType.IMAGE);
myCam.addEventListener(MediaEvent.COMPLETE,selectCompleteHandler);
}
else
{
trace("camera not supported");
statusText.text = "Camera not supported on this device.";
}
}
*/

//select a picture from the camera roll (gallery)
protected function onClickSelectPic():void
{
	if (CameraRoll.supportsBrowseForImage)
	{
		trace("camera roll is supported");
		var roll:CameraRoll = new CameraRoll();
		
		roll.addEventListener(MediaEvent.SELECT,selectCompleteHandler);
		roll.browseForImage();
	}
	else
	{
		trace("camera roll not supported");
		this.wv_main.snapshotMode = true;
		NotiAlert.show(this, "카메라 지원이 되지 않는 기기입니다.");
	}
}


private var dataSource:IDataInput;
//when the selection is complete upload it
protected function selectCompleteHandler(event:MediaEvent):void
{
	//trace("event.data.file.url; = "+event.data.file.url);
	//takePhotoButton.enabled = galleryPhotoButton.enabled = false;
	/*
	if(deviceInfo_os_name == "Android"){
	
	*/
	
	trace( "Media selected..." );
	var imagePromise:MediaPromise = event.data;
	
	if( imagePromise.file != null)
	{
		trace("image file can be selected.");
		var imgFile:File = event.data.file;
		imgFile.addEventListener(Event.COMPLETE, uploadCompleteHandler);
		imgFile.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, receivedHandler);
		imgFile.addEventListener(Event.OPEN,openUploadHandler);
		imgFile.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		
		urlRequest = new URLRequest("http://twitaddons.com/photo/upload_mobile.php/?idx=" + userIdx);
		//urlRequest = new URLRequest("http://twitaddons.com/msg/msg_upload_pic_mobile.php");
		//urlRequest = new URLRequest("http://img.gioo.com/addons/upload_exe_for_app.php");
		
		//trace("sended idx : " + userIdx);
		
		imgFile.upload(urlRequest, "media");
		trace("size is : " + imgFile.size);
		trace("media sended");
	}
	else
	{
		dataSource = imagePromise.open();
		
		if( imagePromise.isAsync )
		{
			trace( "Asynchronous media promise." );
			var eventSource:IEventDispatcher = dataSource as IEventDispatcher;				
			eventSource.addEventListener( Event.COMPLETE, onMediaLoaded );
			//eventSource.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, receivedHandler);
			//eventSource.addEventListener(Event.OPEN,openUploadHandler);
			//eventSource.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		else
		{
			trace( "Synchronous media promise." );
			readMediaData();
		}
	}
}

private function onMediaLoaded( event:Event ):void
{
	trace("Media load complete");
	readMediaData();
}

private var tempDir:File;
private var loader:URLLoader = new URLLoader();
private function readMediaData():void
{
	var imageBytes:ByteArray = new ByteArray();
	dataSource.readBytes( imageBytes );
	
	/*
	tempDir = File.createTempDirectory();
	var now:Date = new Date();
	var filename:String = "IMG" + now.fullYear + now.month + now.day + now.hours + now.minutes + now.seconds + ".jpg";
	var temp:File = tempDir.resolvePath( filename );
	var stream:FileStream = new FileStream();
	*/
	
	
	/*
	stream.open( temp, FileMode.WRITE );
	stream.writeBytes( imageBytes );
	stream.close();
	*/
	
	trace("image length : " + imageBytes.length);
	
	/*
	stream.open( temp, FileMode.READ);
	stream.readBytes(imageBytes);
	
	trace(temp.size);
	*/
	
	
	//
	
	
	
	
	
	
	
	
	//configureListeners(loader);
	loader.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, receivedHandler);
	loader.addEventListener(Event.OPEN,openUploadHandler);
	loader.addEventListener(Event.COMPLETE,uploadCompleteHandler);
	//loader.addEventListener(IOErrorEvent.IO_ERROR, ioError);
	
	
	
	
	
	
	
	//urlRequest = new URLRequest("http://img.gioo.com/addons/upload_exe_for_app.php");
	//urlRequest = new URLRequest("http://www.twitaddons.com/photo/upload_mobile.php/?idx=" + userIdx);
	
	//var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
	//urlRequest.requestHeaders.push(header);
	//urlRequest.method = URLRequestMethod.POST;
	urlRequest.data =  imageBytes;
	
	trace("submiting..");
	
	//loader.load(urlRequest);s
	
	var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");
	urlRequest = new URLRequest("http://img.gioo.com/addons/upload_exe_for_app.php");
	
	urlRequest.requestHeaders.push(header);
	urlRequest.method = URLRequestMethod.POST;
	urlRequest.data = imageBytes;
	
	loader.load(urlRequest);
	
	//temp.upload(urlRequest, "media");
	
}

private function ioErrorHandler(event:IOErrorEvent):void{
	trace("ioError : " + event.toString());
}


private function uploadPic_result(event:ResultEvent):void{
	trace("event is : " + event.result.toString());
}

protected function receivedHandler(event:DataEvent):void{
	
	
	trace("receive string : " + event.text);
	trace("receive string : " + event.data as String);
	trace("receive string : " + event.data);
	wv_main.source = "http://m.twitaddons.com/page/tweet_detail.php?short_id="+escape(event.text);
	
	
	trace("upload complete");
	//takePhotoButton.enabled = galleryPhotoButton.enabled = true;
	
	bi_uploadPic.includeInLayout = false;
	bi_uploadPic.visible = false;
	img_selectPic.includeInLayout = true;
	img_selectPic.visible = true;
	
	trace("complete event : " + event);
}

protected function uploadCompleteHandler(event:Event):void
{
	trace("uploadComplete.");
}

protected function ioError(event:IOErrorEvent):void{
	trace("found ioError");
	this.dispatchEvent(event);
	trace("ioError : " + event.text);
	trace("passed ioError");
}

protected function openUploadHandler(event:Event):void
{
	trace("uploading");
	img_selectPic.includeInLayout = false;
	img_selectPic.visible = false;
	bi_uploadPic.includeInLayout = true;
	bi_uploadPic.visible = true;
}